// pages/user/addressAddorEdit.js
var app = getApp();
var rootDocment = app.globalData.postUrl;
const chooseLocation = requirePlugin('chooseLocation');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '', //小区名字
    address1: '', //门牌号
    name: '', //姓名
    tel: '', //手机号
    active: 0, //标签,
    province: '', //省
    city: '', //市
    county: '', //区
    latitude: '',
    longitude: '',
    id: null,
    m_default: false,
    region: ['请选择收货人地址', '', ''],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options, 'options')
    var that = this
    if (options.id) {
      wx.setNavigationBarTitle({
        title: "修改地址"
      })
      that.setData({
        id: options.id
      });
      app.login(function (userInfo) {
        that.setData({
          userInfo: userInfo
        });
        that.setAddress(options.id);
      });

    } else {
      app.login(function (userInfo) {
        that.setData({
          userInfo: userInfo
        });
      });
      wx.setNavigationBarTitle({
        title: "添加地址"
      })
    }

    //用户授权登录

  },
  getAddress: function () {
    var that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.address']) {
          //已经允许过
          wx.chooseAddress({
            success(res) {

              that.setData({
                // region: [res.provinceName, res.cityName, res.countyName],
                region: [res.provinceName, res.cityName, res.countyName],
                province: res.provinceName,
                city: res.cityName,
                county: res.countyName,
                address: res.detailInfo,
                address1: res.detailInfo,
                name: res.userName,
                tel: res.telNumber,
                latitude: '',
                longitude: '',
              })
              console.log(this.data.region, '=======>')
            }
          })

        } else {
          if (res.authSetting['scope.address'] == false) {
            //如果之前拒绝了就调起设置窗口
            wx.openSetting({
              success(res) {
                console.log(res.authSetting)
              }
            })
          } else {
            //首次允许后
            wx.chooseAddress({
              success(res) {
                that.setData({
                  region: [res.provinceName, res.cityName, res.countyName],
                  province: res.provinceName,
                  city: res.cityName,
                  county: res.countyName,
                  address: res.detailInfo,
                  address1: res.detailInfo,
                  name: res.userName,
                  tel: res.telNumber,
                  latitude: '',
                  longitude: '',
                })
              }
            })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const location = chooseLocation.getLocation();
    if (location) {
      this.setData({
        address: location.name,
        address1: location.name,
        city: location.city,
        county: location.district,
        latitude: location.latitude,
        longitude: location.longitude,
        //name:location.name,
        province: location.province
      })
    }
    console.log(location, 'locationonshow')
  },
  onUnload() {
    console.log('下载了吗')
    chooseLocation.setLocation(null);
  },
  onHide() {
    console.log('8888')
    console.log(chooseLocation.setLocation(null))
    //chooseLocation.setLocation(null);
    console.log(chooseLocation.getLocation(), 'chooseLocation.getLocation()')
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    //chooseLocation.setLocation(null);
    // this.setData({
    //   address: '',
    //   city: '',
    //   district:'',
    //   latitude: '',
    //   longitude: '',
    //   //name:location.name,
    //   province: ''
    // })
  },
  xuandian() {
    const key = 'BGFBZ-MZBLW-LSARC-YIIWM-WPKR5-OCFVM'; //使用在腾讯位置服务申请的key
    const referer = '榴黄树'; //调用插件的app的名称
    const location = JSON.stringify({
      latitude: this.data.latitude,
      longitude: this.data.longitude
    });
    if (!!this.data.latitude) {
      wx.navigateTo({
        url: `plugin://chooseLocation/index?key=${key}&location=${location}&referer=${referer}`
      });
    } else {
      wx.navigateTo({
        url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
      });
    }
    // const category = '生活服务,娱乐休闲';


  },
  //获取地址信息
  setAddress: function (id) {
    chooseLocation.setLocation(null);
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    var paraArr = new Array();
    paraArr['id'] = id;
    paraArr['user_id'] = that.data.userInfo.userID;
    var sign = app.signature(paraArr);
    wx.request({
      url: rootDocment + '/api_address/' + id,
      data: {
        user_id: paraArr['user_id'],
        sign: sign
      },
      method: 'GET',
      header: {},
      success: function (res) {
        wx.hideLoading()
        that.setData({
          region: [res.data.province, res.data.city, res.data.county],
          province: res.data.province,
          city: res.data.city,
          county: res.data.county,
          latitude: res.data.latitude,
          longitude: res.data.longitude,
          //region: ['河南省', '郑州市', '高新区'],
          id: id,
          address: res.data.address,
          address1: res.data.address1 ? res.data.address1 : res.data.address,
          name: res.data.name,
          tel: res.data.tel,
          isdefault: res.data.is_default,
          active: res.data.label,
          m_default: res.data.is_default == '0' ? false : true,
          hiddenLoading: true
        });
      }
    })
  },
  //删除地址
  delAddress: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var paraArr = new Array();
    paraArr['id'] = id;
    paraArr['user_id'] = that.data.userInfo.userID;
    var sign = app.signature(paraArr);
    wx.showModal({
      title: '提示',
      content: '确认要删除吗！',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: rootDocment + '/api_address/' + id,
            data: {
              user_id: paraArr['user_id'],
              sign: sign
            },
            method: 'DELETE',
            header: {},
            success: function (res) {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      }
    })
  },
  bindRegionChange: function (e) {
    console.log(e);
    this.setData({
      region: e.detail.value
    })
  },
  formSubmit: function (e) {
    var that = this;
    var m_province = this.data.region[0];
    var m_city = this.data.region[1];
    var m_county = this.data.region[2];
    var m_addr = this.data.address;
    var m_address1 = this.data.address1;
    var m_label = this.data.active
    let m_latitude = this.data.latitude
    let m_longitude = this.data.longitude
    var m_name = this.data.name;
    var m_tel = this.data.tel;
    var m_id = this.data.id;
    var m_default = this.data.m_default;
    if (m_default) {
      m_default = 1;
    } else {
      m_default = 0;
    }
    console.log(m_province, 'm_addr')
    if (m_province == "请选择收货人地址") {

      wx.showToast({
        title: '请选择收货人地址',
        icon: 'none'
      })
      return false;
    }
    if (!m_address1) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      // wx.showModal({
      //   title: '提示',
      //   content: ''
      // })
      return false;
    }

    if (m_name == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false;
    }
    if (m_tel == '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return false;
    }



    // m_tel = m_tel.replace(/\s+/g, '')

    // var myreg = /^1[23456789]\d{9}$/
    // if (!myreg.test(m_tel)) {
    //   wx.showToast({
    //     title: '手机号码不正确！',
    //     icon: 'none'
    //   })
    //   return false;
    // }
    let id = this.data.id ? '/' + m_id : ''
    let method = this.data.id ? 'put' : 'post'
    //return
    wx.request({
      url: rootDocment + '/api_address' + id,
      data: {
        m_province: m_province,
        m_city: m_city,
        m_county: m_county,
        m_address: m_addr,
        m_name: m_name,
        m_tel: m_tel,
        m_latitude: m_latitude,
        m_longitude: m_longitude,
        m_address1: m_address1,
        m_default: m_default,
        m_label: m_label,
        user_id: that.data.userInfo.userID
      },
      method: method,
      header: {},
      success: function (res) {
        if (res.data.code == '1001') {
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  inputChange: function (e) { //输入框双向绑定
    console.log(e, 'e')
    this.setData({
      [e.target.dataset.id]: e.detail.value
    })
  },
  onChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    console.log(detail)
    this.setData({
      m_default: detail
    });
  },
  inputClose: function (e) { //输入框双向绑定
    console.log(e, 'e')
    this.setData({
      [e.currentTarget.dataset.name]: ''
    })
  },
  labelClick: function (e) { //输入框双向绑定
    let id = e.currentTarget.dataset.id
    console.log(e, 'e')
    if (this.data.active == id) {
      this.setData({
        active: 0
      })
    } else {
      this.setData({
        active: id
      })
    }

    console.log(this.data.active)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  // onHide() {

  // },

  /**
   * 生命周期函数--监听页面卸载
   */
  // onUnload() {

  // },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})